# vimeo.com plugin for XBMC (all platforms?)

from BeautifulSoup import BeautifulStoneSoup
import xbmcutils.net
import xbmc, xbmcgui, xbmcplugin
import os,sys,urllib,md5,re

# constants
__plugin__ = "vimeo-xbmc"
__author__ = "fiatpandas"
__url__ = "http://code.google.com/p/vimeo-xbmc/"
__svn_url__ = "http://vimeo-xbmc.googlecode.com/svn/trunk/plugins/video/vimeo-xbmc/"
__version__ = "v3"

api_key = xbmcplugin.getSetting("api_key")
api_secret = xbmcplugin.getSetting("api_secret")
hd_video = xbmcplugin.getSetting("hd_video")

#relevant|newest|oldest|plays|comments|likes
#    0      1       2     3      4       5

sortType = xbmcplugin.getSetting("sortType")

if sortType == '0':
  sortType = 'relevant'
elif sortType == '1':
  sortType = 'newest'
elif sortType == '2':
  sortType = 'oldest'
elif sortType == '3':
  sortType = 'plays'
elif sortType == '4':
  sortType = 'comments'
else:
  sortType = 'likes'


def mainMenu():
  addOption("Search Videos",1,os.getcwd()+'\\search.png')
  addOption("Play Video ID",3,os.getcwd()+'\\playID.png')



def getInput(message):
  kb = xbmc.Keyboard('', message, False)
  kb.doModal()
  
  if (kb.isConfirmed()):
    textInput = kb.getText()
  return textInput



def getFLVLoc(clipID):
  requestURL = 'http://vimeo.com/moogaloop/load/clip:'+clipID+'/'
  soupTree = getResults(requestURL)

  request_signature = soupTree('request_signature')[0].renderContents()
  request_signature_expires = soupTree('request_signature_expires')[0].renderContents()
  
  vidQuality = "hq"
  
  if hd_video == "true":
    vidQuality = "hd"
    
  flvURL = 'http://vimeo.com/moogaloop/play/clip:' \
           + clipID + '/' + request_signature \
           + '/' + request_signature_expires \
           + '/?q=' + vidQuality
  return flvURL



def playVideoID(clipID):
  flvURL = getFLVLoc(clipID)
  xbmc.Player().play(flvURL)



def getResults(url):
  reqHeader = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10'}
  data = xbmcutils.net.retrieve(url, None, reqHeader)
  return BeautifulStoneSoup(data, convertEntities=BeautifulStoneSoup.HTML_ENTITIES)



def searchVimeo(query, pgNum): 
  searchRequest = 'http://www.vimeo.com/videos/search:'+urllib.quote_plus(query)+'/page:'+str(pgNum)+'/sort:'+sortType+'/'
   
  soupTree = getResults(searchRequest)
  
  items = soupTree('div',attrs={"class":re.compile("^item")})
  nResults = len(items)
  titles = soupTree('div',attrs={"class":re.compile("^title")})
  
  for node in range(nResults):
    vidID = items[node]('a')[0]['href'][1:].encode('UTF-8')
    vidTitle = titles[node]('a')[0].contents[0]
    vidThumb = items[node]('img')[0]['src'].encode('UTF-8')
    addVideos(vidID,vidTitle,vidThumb)
    
  return nResults



def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param



def addOption(name,mode,thumbnail):
  u=sys.argv[0]+"?mode="+str(mode)
  ok=True
  liz=xbmcgui.ListItem(name, iconImage='DefaultFolder.png',thumbnailImage=thumbnail)
  liz.setInfo( type="Video", infoLabels={ "Title": name } )
  ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
  return ok



def addVideos(ID, name, thumbnail):
  u=sys.argv[0]+"?mode=2"+"&videoID="+str(ID)
  liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=thumbnail)
  liz.setInfo( type="Video", infoLabels={ "Title": name } )
  ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz)



def addNextPage(page, query):
  u=sys.argv[0]+"?mode="+str(mode)+"&searchPage="+str(page)+"&query="+urllib.quote_plus(query)
  ok=True
  liz=xbmcgui.ListItem("Next Page", iconImage="DefaultFolder.png", thumbnailImage=os.getcwd()+'\\next.png')
  liz.setInfo( type="Video", infoLabels={ "Title": "Next page" } )
  ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
  return ok


  
params=get_params()

mode=None
searchPage='1'
query=None
videoID=None

try:
  mode=int(params["mode"])
except:
  pass
try: 
  searchPage=params["searchPage"]
except:
  pass
try: 
  query=params["query"]
except:
  pass
try: 
  videoID=params["videoID"]
except:
  pass

if mode==None:
        mainMenu()
        
#
# mode 1: return search results (titles + thumbnails)
#        
        
elif mode==1:
  if searchPage == '1':
    query = str(getInput('Specify search query'))
  nResults = searchVimeo(query,searchPage)
  if nResults == 12:
    searchPage = int(searchPage)+1
    addNextPage(searchPage, query)

#
# mode 2: individual video results link to mode 2, 
# which sends an FLV location to the XBMC player
#

elif mode==2:
  playVideoID(videoID)

#
# mode 3: play video using known video ID
#

elif mode==3:
   query = str(getInput('Specify a video ID to play'))
   playVideoID(query)
   mainMenu()
   
xbmcplugin.endOfDirectory(int(sys.argv[1]))
